<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/3/003
 * Time: 13:26
 */
namespace app\common\job;

use app\common\self\SelfRedis;
use think\facade\Log;
use think\queue\Job;
class FileUploadsJob
{
    public $desc = '推送到列表中等待上传';

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data)
    {
        ini_set('memory_limit','512M');
        //send_telegram($msg);
        $this->_doJob($data);
        fileLog(date('Y-m-d H:i:s').'---'.$this->desc.'开始中---','FileUploads.log');
        // 一定要删除  不然会重复跑
        $job->delete();
        fileLog(date('Y-m-d H:i:s').'---'.$this->desc.'结束了---','FileUploads.log');
        return;
    }

    /**
     * 业务处理
     *
     * @param $data
     * @return bool|int
     */
    private function _doJob($data){
        fileLog(date('Y-m-d H:i:s').'---数据如下---','FileUploads.log');
        // 数据格式
        /*
        $data = [
            'file' =>'绝对-本地存储的路劲',
            "cos_path" => 'cos云对象存储路劲',
            "id" => "id",
            'table' => '数据表名',
            'data' => [
                "字段名" => "字段值"
            ],
            'del' => false, 表示不删除  默认 true 删除
        ];
         */
        // 是否有绝对路劲 且  有该文件路劲
        if(!$data || !is_array($data) || !isset($data['file']) || !isset($data['cos_path']))return false;
        // 如果没有该文件
        if(!file_exists($data['file'])){
            fileLog(date('Y-m-d H:i:s').'---文件不存在---:'.$data['file'],'FileUploads.log');
            return false;
        }

        // 初始化cos对象  并且上传中
        $cosConfig = config('cos');
        $secretId = $cosConfig['secretId']; //"云 API 密钥 SecretId";
        $secretKey = $cosConfig['secretKey']; //"云 API 密钥 SecretKey";
        $region = $cosConfig['region']; //设置一个默认的存储桶地域
        # 创建存储对象
        $cosClient = new \Qcloud\Cos\Client([
                'region' => $region,
                #'schema' => 'https', //协议头部，默认为http
                'credentials'=> ['secretId'  => $secretId ,'secretKey' => $secretKey]]
        );
        $file = file_get_contents($data['file']);
        ### 上传文件流
        try {    
            $bucket = $cosConfig['bucket']; //存储桶名称 格式：BucketName-APPID
            if ($file) {
                $result = $cosClient->putObject([
                    "Bucket"=>$bucket,
                    "Key"=>$data['cos_path'],
                    "Body"=>$file
                ]);
                fileLog(date('Y-m-d H:i:s').'---上传数据ok,打印数据如下：---:'.json_encode([
                    'data' => $data,
                    'uploads' => $result
                ]),'FileUploads.log');
                if(!isset($data['table']) || !isset($data['id']) || !$data['id'] || !$data['table']) return;
                fileLog(date('Y-m-d H:i:s').'---开始处理mysql操作---:','FileUploads.log');
                if($data['table'] && $model = unserialize($data['table'])){
                    fileLog(date('Y-m-d H:i:s').json_encode($model->find($data['id'])),'FileUploads.log');
                    $a = $model->where('id',$data['id'])->update($data['data']);
                    // 更新成功，且 当前默认为删除
                    if($a &&  (!isset($data['del']) || $data['del']) )unlink($data['file']);
                }
                /*
                $table = Db::table($data['table']);
                if($table){
                    $table->where('id',$data['id'])->update([

                    ]);
                }
                 */
            }
        } catch (\Exception $e) {
            fileLog(date('Y-m-d H:i:s').'---异常抛出处理---:'.$data['file'],'FileUploads.log'); 
        }
    }

    // 处理失败
    public function failed($data){

    }
}